package com.linwankaifa.linwancunyi.ui.doctor;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.ChatrecordBean;
import com.linwankaifa.linwancunyi.ui.adapter.DoctorMsgAdapter;
import com.linwankaifa.linwancunyi.util.Data_whole;
import com.linwankaifa.linwancunyi.util.JsonTransformation;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 余梦麒 on 2019/7/13.
 */

public class DoctorChat extends AppCompatActivity {

    String SHAREDPREFERENCES_NAME = "shared.xml";
    SharedPreferences preferences;
    ChatrecordBean chatrecordBean;
    SharedPreferences.Editor editor;
    int chatnumber;
    Timer timer;
    TimerTask timerTask;
    TextView name;
    TextView sex;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_chat);

        preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);

        chatnumber = 0;

        name = (TextView) findViewById(R.id.doctor_chat_patient_name);
        sex = (TextView) findViewById(R.id.doctor_chat_patient_sex);
        name.setText(Data_whole.getPatientBean().getPatientname());
        sex.setText(Data_whole.getPatientBean().getPatientsex());

        init();

    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initTimer();
    }

    private void initTimer() {


        timer = new Timer();

        timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        init();

                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 5000);

    }


    private void init() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = null;


        // 获取编辑框中的值


        chatrecordBean = new ChatrecordBean();

        chatrecordBean.setDoctorid(Data_whole.getDoctorBean().getDoctorid());
        chatrecordBean.setPatientid(Data_whole.getPatientBean().getPatientid());

        requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                JsonTransformation.objectToJson(chatrecordBean));

        // 根据不同的角色构建不同的url
        String url = getString(R.string.url)+"/";
        url += preferences.getString("usertype", "");
        url += "/getchatinfo";

        // 构建请求体，并执行
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 如果失败，就显示失败信息
                Toast toast = Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断请求是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (isSuccess) {
                            case "404":
                                Toast.makeText(getApplicationContext(), "查询错误", Toast.LENGTH_SHORT).show();
                                break;
                            case "200":
                                // 如果成功过则进行业务逻辑操作
                                Toast.makeText(getApplicationContext(), "获取聊天错误", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                List<ChatrecordBean> chatrecordlist = JsonTransformation.jsonToList(isSuccess, ChatrecordBean.class);
                                int number = chatrecordlist.size();
                                if (number != chatnumber) {
                                    ListView listView = (ListView) findViewById(R.id.doctor_chat_list_view);
                                    listView.setAdapter(new DoctorMsgAdapter(DoctorChat.this, R.layout.list_msg_layout1, chatrecordlist));
                                    chatnumber = number;
                                }
                                break;
                        }
                    }
                });
            }
        });
    }

    public void send(View view) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = null;

        // 获取编辑框中的值


        ChatrecordBean newchat = new ChatrecordBean();

        newchat.setDoctorid(Data_whole.getDoctorBean().getDoctorid());
        newchat.setPatientid(Data_whole.getPatientBean().getPatientid());
        switch (preferences.getString("usertype", "")) {
            case "patient":
                newchat.setIspatienttodoctor(1);
                break;
            case "doctor":
                newchat.setIspatienttodoctor(0);
                break;
        }
        final EditText editText = (EditText) findViewById(R.id.doctor_chat_edit);
        newchat.setChatcontent(editText.getText().toString());

        requestBody = RequestBody.create(MediaType.parse("text; charset=utf-8"),
                JsonTransformation.objectToJson(newchat));

        // 根据不同的角色构建不同的url
        String url = getString(R.string.url)+"/";
        url += preferences.getString("usertype", "");
        url += "/chat";

        // 构建请求体，并执行
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 如果失败，就显示失败信息
                Toast toast = Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断请求是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (isSuccess) {
                            case "404":
                                Toast.makeText(getApplicationContext(), "无法获取记录", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                List<ChatrecordBean> chatrecordlist = JsonTransformation.jsonToList(isSuccess, ChatrecordBean.class);
                                int number = chatrecordlist.size();
                                if (number != chatnumber) {
                                    ListView listView = (ListView) findViewById(R.id.doctor_chat_list_view);
                                    listView.setAdapter(new DoctorMsgAdapter(DoctorChat.this, R.layout.list_msg_layout1, chatrecordlist));
                                    chatnumber = number;
                                    editText.setText("");
                                }
                                break;
                        }
                    }
                });
            }
        });

    }

    public void doctorsend(View view) {
        send(view);
    }

    public void back(View view) {
        this.finish();
    }
}

